﻿using System;
using Splendor_Server.script.db;
using Splendor_Server.script.logic.player;
using Splendor_Server.script.net;

namespace Splendor_Server.script.logic.msg
{
    public partial class MsgHandler
    {
        //注册协议处理
        public static void MsgRegister(ClientState client, MsgBase msgBase)
        {
            
            MsgRegister msg = (MsgRegister) msgBase;

            RegisterResult result = DbManager.Register(msg.id, msg.pw);

            if (result == RegisterResult.Successful)
                result = DbManager.CreateNewPlayer(msg.id);

            msg.result = (int) result;
            NetManager.Send(client, msg);
        }

        //登陆协议处理
        public static void MsgLogin(ClientState client, MsgBase msgBase)
        {
            MsgLogin msg = (MsgLogin) msgBase;
            //密码校验 | 不允许再次登陆 TODO 切换账号？
            if (client.player != null || PlayerManager.IsOnline(msg.id))
            {
                //已经登录了账号/账号已在别处登录
                // //发送踢下线协议
                // Player other = PlayerManager.GetPlayer(msg.id);
                // MsgKick msgKick = new MsgKick {reason = 1};
                // other.Send(msgKick);
                // //断开连接
                // NetManager.Close(other.client);
                msg.result = (int) LoginResult.IsOnline;
                NetManager.Send(client, msg);
                return;
            }

            LoginResult result = DbManager.Login(msg.id, msg.pw);
            msg.result = (int) DbManager.Login(msg.id, msg.pw);

            if (result != LoginResult.Successful)
            {
                NetManager.Send(client, msg);
                return;
            }

            //获取玩家数据
            PlayerData playerData = DbManager.GetPlayerData(msg.id);
            if (playerData == null)
            {
                msg.result = (int) LoginResult.Other;
                NetManager.Send(client, msg);
                return;
            }

            Player player = new Player(client, msg.id, playerData);
            PlayerManager.AddPlayer(msg.id, player);
            client.player = player;

            player.Send(msg);
        }
    }
}